package xiyuan.data;

import java.sql.Timestamp;
import java.util.LinkedList;
import java.util.List;

import xiyuan.keywords.tfidf.KeyWord;

public class DatabaseUtil {
	/**
	 * write the keywords of a user to database
	 * @param uid	
	 * @param list
	 * @return
	 */
	public static boolean writeKeywords(long uid, List<KeyWord> list){
		KeywordDAO dao = new KeywordDAO();
		dao.getSession().clear();
		//clear all existing keywords of this user
		List existingKeywords = dao.findByUid(uid + "");
		for (Object keyword : existingKeywords){
			dao.delete((Keyword) keyword);
		}
		
		//write new keywords
		Timestamp curTime = new Timestamp(System.currentTimeMillis());
		for (KeyWord word:list){
			dao.save(new Keyword(""+uid, word.getWord(), 
					word.getValue(), curTime));
		}
		dao.getSession().flush();
		dao.getSession().close();
		return false;
	}

	private static final int EXPIRE_DAY = 20;
	public static boolean userExist(long uidF) {
		KeywordDAO dao = new KeywordDAO();
		List<?> list = dao.findByUid(""+uidF);
		if (list.size() == 0)
			return false;
		Keyword keyword = (Keyword) list.get(0);
		return keyword.getDate().after(new Timestamp(
				System.currentTimeMillis() - 
				1000 * 60 * 60 * 24 * EXPIRE_DAY));
	}

	public static List<KeyWord> getKeywordByUID(long uidF) {
		KeywordDAO dao = new KeywordDAO();
		List<?> list = dao.findByUid("" + uidF);
		List<KeyWord> listN = new LinkedList<KeyWord>();
		for (Object obj: list){
			Keyword keyword = (Keyword) obj;
			listN.add(new KeyWord(
					keyword.getKeyword(), keyword.getWeight()));
		}
		return listN;
	}
}
